package com.zealfi.wk.netty.chat;

import com.zealfi.wk.netty.chat.handler.inbound.HttpRequestHandler;
import com.zealfi.wk.netty.chat.handler.inbound.TextWebSocketFrameHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * Created by kuan at 2018-06-13 上午 10:28
 */
//1.扩展 ChannelInitializer
public class ChatServerInitializer extends ChannelInitializer {
    private final ChannelGroup group;

    public ChatServerInitializer(ChannelGroup group) {
        this.group = group;
    }

    @Override
    //2.添加 ChannelHandler　到 ChannelPipeline
    protected void initChannel(Channel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //职责：Decode bytes to HttpRequest, HttpContent, LastHttpContent.
        // Encode HttpRequest, HttpContent, LastHttpContent to bytes.
        pipeline.addLast(new HttpServerCodec());
        //职责：Write the contents of a file.
        pipeline.addLast(new HttpObjectAggregator(64 * 1024));
        //职责：This ChannelHandler aggregates an HttpMessage and its following HttpContents into a single FullHttpRequest or
        // FullHttpResponse (depending on whether it is being used to handle requests or responses).With this installed the
        // next ChannelHandler in the pipeline will receive only full HTTP requests.
        pipeline.addLast(new ChunkedWriteHandler());
        //职责：Handle FullHttpRequests (those not sent to "/ws" URI).
        pipeline.addLast(new HttpRequestHandler("/ws"));
        //职责：As required by the WebSockets specification, handle the WebSocket Upgrade handshake, PingWebSocketFrames,
        // PongWebSocketFrames and CloseWebSocketFrames.
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        //职责：Handles TextWebSocketFrames and handshake completion events
        pipeline.addLast(new TextWebSocketFrameHandler(group));
    }
}
